package com.jisu.controller;

import com.jisu.common.ResultVo;
import com.jisu.dto.DealerDTO;
import com.jisu.pojo.Dealer;
import com.jisu.service.DealerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RefreshScope
@RequestMapping("/dealer")
public class DealerController {

    @Autowired
    private DealerService dealerService;

    // 新增经销商
    @PostMapping("/addDealer")
    public ResultVo addDealer(@RequestBody Dealer dealer) {
        dealer.setDealerId(null); // 确保自动生成ID
        if (dealerService.save(dealer)) {
            return ResultVo.success("添加成功", 200);
        } else {
            return ResultVo.fail("添加失败", 500);
        }
    }

    // 批量删除经销商
    @DeleteMapping("/deleteDealersByIds/{ids}")
    public ResultVo deleteDealers(@PathVariable List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return ResultVo.fail("未选中经销商！");
        }
        try {
            boolean deleteRows = dealerService.removeBatchByIds(ids);
            if (deleteRows) {
                return ResultVo.success("删除成功");
            } else {
                return ResultVo.fail("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.fail("未知错误");
        }
    }

    // 更新经销商信息
    @PutMapping("/updateDealerById/{id}")
    public ResultVo updateDealerById(@PathVariable Integer id, @RequestBody Dealer dealer) {
        Dealer existingDealer = dealerService.getById(id);
        if (existingDealer == null) {
            return ResultVo.fail("经销商不存在");
        }

        dealer.setDealerId(id);
        try {
            boolean result = dealerService.updateById(dealer);
            if (result) {
                return ResultVo.success("更新成功");
            } else {
                return ResultVo.fail("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.fail("未知错误");
        }
    }

    // 根据ID查询经销商
    @GetMapping("/getDealerInfo")
    public Dealer getDealerInfo(@RequestParam("id") Long id) {
        return dealerService.getById(id);
    }

    // 条件查询经销商
    @GetMapping("/searchDealersByDTO")
    public ResultVo<List<Dealer>> searchDealersByDTO(DealerDTO dealerDTO) {
        List<Dealer> dealers = dealerService.searchDealersByDTO(dealerDTO);
        return ResultVo.success("查询成功", dealers);
    }
}
